Page({
  data: {
    form: {
      name: '',
      idCard: '',
      phone: '',
      hukouAddress: '',
      liveAddress: '',
      location: '',
      area: '',
      reason: '',
      idCardImage: '',
      householdImage: '',
      landProofImage: ''
    },
  // 全局加载状态
  globalLoading: false,
  globalLoadingText: '服务事项加载中...',

  // 显示全局加载
  showGlobalLoading(text = '服务事项加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

    applyTypes: ['新建', '翻建', '危房重建', '扩建'],
    typeIndex: -1,

    usages: ['住宅', '附属用房', '生产辅助'],
    usageIndex: -1,

    agreed: false,
    canSubmit: false,
    errors: {},
    showErrors: false
  },

  onInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    this.setData({ [`form.${field}`]: value }, this.validateForm);
  },

  onTypeChange(e) {
    const value = Number(e.detail.value);
    this.setData({ typeIndex: value }, this.validateForm);
  },

  onUsageChange(e) {
    const value = Number(e.detail.value);
    this.setData({ usageIndex: value }, this.validateForm);
  },

  onUploadIdCard() { this.chooseAndUploadImage('idCardImage'); },
  onUploadHousehold() { this.chooseAndUploadImage('householdImage'); },
  onUploadLandProof() { this.chooseAndUploadImage('landProofImage'); },

  chooseAndUploadImage(fieldName) {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = (res.tempFiles && res.tempFiles[0] && res.tempFiles[0].tempFilePath) || '';
        if (!tempFilePath) { return; }
        setTimeout(() => {
          this.setData({ [`form.${fieldName}`]: tempFilePath }, this.validateForm);
          wx.showToast({ title: '上传成功', icon: 'success' });
        }, 600);
      }
    });
  },

  onDeclarationChange(e) {
    const agreed = (e.detail.value || []).includes('agree');
    this.setData({ agreed }, this.validateForm);
  },

  validateForm() {
    const { form, typeIndex, usageIndex, agreed, showErrors, applyTypes, usages } = this.data;

    const requiredFields = ['name', 'idCard', 'phone', 'hukouAddress', 'liveAddress', 'location', 'area', 'reason'];
    const isBasicValid = requiredFields.every(key => !!(form[key] && String(form[key]).trim()));

    const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    const phoneRegex = /^1[3-9]\d{9}$/;
    const areaNum = Number(form.area);
    const isAreaValid = !isNaN(areaNum) && areaNum > 0;

    const isImagesValid = !!form.idCardImage && !!form.householdImage;
    const isPickersValid = typeIndex >= 0 && usageIndex >= 0 && !!applyTypes[typeIndex] && !!usages[usageIndex];

    const canSubmit = isBasicValid && isImagesValid && isPickersValid && idCardRegex.test(form.idCard) && phoneRegex.test(form.phone) && isAreaValid && agreed;

    const errors = {};
    if (showErrors) {
      requiredFields.forEach((k) => {
        if (!form[k] || !String(form[k]).trim()) {
          const names = {
            name: '姓名', idCard: '身份证号', phone: '联系电话',
            hukouAddress: '户籍地址', liveAddress: '现居住地址', location: '拟建位置', area: '拟建面积', reason: '申请事由'
          };
          errors[k] = `请填写${names[k]}`;
        }
      });
      if (!form.idCardImage) errors.idCardImage = '请上传身份证照片';
      if (!form.householdImage) errors.householdImage = '请上传户口簿照片';
      if (form.idCard && !idCardRegex.test(form.idCard)) errors.idCard = '身份证号格式不正确';
      if (form.phone && !phoneRegex.test(form.phone)) errors.phone = '手机号格式不正确';
      if (!isAreaValid) errors.area = '请输入大于0的面积数值';
      if (!(typeIndex >= 0)) errors.applyType = '请选择申请类型';
      if (!(usageIndex >= 0)) errors.usage = '请选择建设用途';
      if (!agreed) errors.agreed = '请勾选申请声明';
    }

    this.setData({ canSubmit, errors });
  },

  onSubmit() {
    this.setData({ showErrors: true }, () => {
      this.validateForm();
      if (!this.data.canSubmit) {
        wx.showToast({ title: '请完善申请信息', icon: 'none' });
        return;
      }
      setTimeout(() => {
        wx.showModal({
          title: '申请提交成功',
          content: '您的宅基地申请已提交，我们将在3-5个工作日内完成审核。',
          showCancel: false,
          confirmText: '确定',
          success: () => { wx.navigateBack({ delta: 1 }); }
        });
      }, 1500);
    });
  }
});


